package com.sghd.charge.controller;

import com.sghd.charge.module.model.ChannelType;
import com.sghd.charge.module.payment.ChannelProcessor;
import com.sghd.common.utils.codec.CryptUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 抽象充值接口
 */
public abstract class AbstractController implements ApplicationContextAware {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**spring容器*/
    protected ApplicationContext applicationContext;

    private ConcurrentMap<ChannelType, ChannelProcessor> processors;

    @PostConstruct
    void init() {
        Map<String, ChannelProcessor> beans = applicationContext.getBeansOfType(ChannelProcessor.class);
        processors = new ConcurrentHashMap<>(beans.size());
        for (ChannelProcessor processor : beans.values()) {
            ChannelProcessor prev = processors.put(processor.getType(), processor);
            if (prev != null) {
                FormattingTuple message = MessageFormatter.format("频道充值处理器重复添加[{}]", prev);
                logger.error(message.getMessage());
                throw new RuntimeException(message.getMessage());
            }
        }
    }

    protected ChannelProcessor getProcessor(ChannelType channelType) {
        return processors.get(channelType);
    }

    /** 检查是否有效的签名信息 */
    public static boolean chkSign(String key, String sign, Object... params) {
        StringBuilder sb = new StringBuilder();
        for (Object s : params) {
            sb.append(s);
        }
        sb.append(key);
        boolean valid = false;
        try {
            String str = CryptUtils.md5(sb.toString());
            if (str.equalsIgnoreCase(sign)) {
                valid = true;
            }
        } catch (Exception e) {
            valid = false;
        }
        return valid;
    }

    /**
     * 检查充值信息是否合法
     * @param operator 运营商对象
     * @param money 充值金额
     * @param gold 充值金币
     * @return true:合法, false:非法
     */
    protected boolean isValidChargeInfo(int money, int gold) {
        if (money <= 0) {
            return false;
        }
        if (gold < 0) {
            return false;
        }
        return true;
    }

    /**
     * 检查访问IP是否合法
     * @param operator 运营商对象
     * @param ip 访问IP
     */
    protected void chkRemoteAddr(String ip) {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
